// ========================定制项目图片上传处理===切边上传============================
var imgReaderl = new FileReader();
var regexImageFiler = /^(?:image\/bmp|image\/png|image\/jpeg|image\/jpg|\/gif)$/i;
// 调起系统文件选择框方法
var imgChange = $(".imgChange").prev().prev();
var imgfFilemaxSize, ThisImgInput, ThisImgInputName, ThisImg, imgUrl;
var thisImgclick;
$("body").on("click", ".imgChange", function(e) {
    //触发 文件选择的click事件
    thisImgclick = $(this);
    $("#file").trigger("click"); //模拟单击
    thisIMg = $(this).prev().prev();
    ThisImgInput = $(this).prev();
    // thisIMg.attr("src", "ewrwrre");
});
var imgfFile;

function fileOnchange(e) {
    //   var imgBase64Url = $("#file").attr("value");
    imgUrl = $("#file").val();
    imgfFile = $("#file").prop("files")[0]; //获取选择文件
    // console.log('imgfFile', imgfFile)
    var size = imgfFile.size; //注意，这里读到的是字节数
    imgfFilemaxSize = size / 1024; //转化为字节
}

// 压缩图片
async function lrzfun(imgUrl, imgfFile, thisIMg, ThisImgInput, IMgwidth, msg) {
    try {
        lrz(imgfFile, {
                width: IMgwidth,
            })
            .then(function(rst) {
                if (rst != "" && rst != null && rst != undefined && rst != "undefined") {
                    var rstBlob = rst.file; //blobToFile
                    var rstBlobName = rst.origin.name || null;
                    var index = rstBlobName.lastIndexOf("/");
                    var imgName = timestamp() + rstBlobName.substring(index + 1, rstBlobName.length);
                    // console.log(imgName)
                    var file2 = new File([rstBlob], imgName, {
                        type: "image/jpg",
                        lastModified: Date.now(),
                    });
                    var size = file2.size; //注意，这里读到的是字节数
                    var imgFilemaxSize = parseFloat(size / 1024).toFixed(4); //转化为字节
                    // console.log('imgFilemaxSize', imgFilemaxSize)
                    upload(imgUrl, file2, thisIMg, ThisImgInput);
                }
                return rst;
            })
            .then(function(rst) {
                return rst;
            })
            .catch(function(err) {
                // alert(err);
                console.log(err);
            })
            .always(function() {
                // console.log(msg)
            });
    } catch (error) {
        console.log("async", error);
    }
    return true;
}

/* ==================================================== */
// 压缩图片方法
var yasuoNB = 0,
    imgName,
    imgName2;
document.querySelector("#file").addEventListener("change", function(e) {
    try {
        imgUrl = $("#file").val() || null;
        imgfFile = $("#file").prop("files")[0] || null; //获取选择文件

        var size = imgfFile.size; //注意，这里读到的是字节数
        imgfFilemaxSize = parseFloat(size / 1024).toFixed(4); //转化为字节

        if (!regexImageFiler.test(imgfFile.type)) {
            layer.confirm("请选择有效图片");
        } else {
            if (imgfFilemaxSize > 9612) {
                layer.confirm("请提交容量10240KB(10MB)字节以下大小的图片文件！" + imgfFilemaxSize);
                console.log("图片大于10240kb");
                yasuoNB = 10;
            } else if (imgfFilemaxSize > 7000 && imgfFilemaxSize < 9612) {
                lrzfun(imgUrl, imgfFile, thisIMg, ThisImgInput, 1180, "图片大于7000小于10240");
                yasuoNB = 9;
            } else if (imgfFilemaxSize > 6000 && imgfFilemaxSize < 7000) {
                lrzfun(imgUrl, imgfFile, thisIMg, ThisImgInput, 1080, "图片大于6000小于7000");
                yasuoNB = 8;
            } else if (imgfFilemaxSize > 5000 && imgfFilemaxSize < 6000) {
                lrzfun(imgUrl, imgfFile, thisIMg, ThisImgInput, 960, "图片大于5000小于6000");
                yasuoNB = 7;
            } else if (imgfFilemaxSize > 4000 && imgfFilemaxSize < 5000) {
                lrzfun(imgUrl, imgfFile, thisIMg, ThisImgInput, 860, "图片大于4000小于5000");
                yasuoNB = 6;
            } else if (imgfFilemaxSize > 3000 && imgfFilemaxSize < 4000) {
                lrzfun(imgUrl, imgfFile, thisIMg, ThisImgInput, 760, "图片大于3000小于4000");
                yasuoNB = 5;
            } else if (imgfFilemaxSize > 2000 && imgfFilemaxSize < 3000) {
                lrzfun(imgUrl, imgfFile, thisIMg, ThisImgInput, 660, "图片大于2000小于3000");
                yasuoNB = 4;
            } else if (imgfFilemaxSize > 1000 && imgfFilemaxSize < 2000) {
                lrzfun(imgUrl, imgfFile, thisIMg, ThisImgInput, 560, "图片大于1000小于2000");
                yasuoNB = 3;
            } else if (imgfFilemaxSize > 100 && imgfFilemaxSize < 1000) {
                lrzfun(imgUrl, imgfFile, thisIMg, ThisImgInput, 460, "图片大于100小于1000");
                yasuoNB = 2;
            } else if (imgfFilemaxSize < 100) {
                upload(imgUrl, imgfFile, thisIMg, ThisImgInput);
                yasuoNB = 1;
                console.log("图片小于100");
            } else if (imgfFilemaxSize < 5) {
                yasuoNB = 0;
                layer.confirm("请替换其他图片！");
            }

            imgName = imgfFile.name;
        }

        // }
    } catch (error) {
        console.log(error);
    } finally {
        e.srcElement.value = "";
        console.log("清空inputImgfile");
    }
});
/* ==================================================== */

// 阿里云OSS提交图片
var client = new OSS.Wrapper({
    region: "oss-cn-shenzhen", //阿里云获取
    //   accessKeyId: "LTAI5tHqQx4GmMu4osB4D4Dm",//自己的子账户
    //   accessKeySecret: "lOj5dQBmLDeGFqMBT4g229eDHf0sx21",
    accessKeyId: "LTAI5t6zdkiGK83mkd36Xpe7", //自己的主账户
    accessKeySecret: "0JsypxPQBWY9LrTgHpuds7JMFU1Vmz",
    bucket: "zhilai-baojia", //要存储的目录名
    // region: "oss-cn-shanghai", //阿里云获取 别人的key
    // accessKeyId: "LTAI3M6GxA5Cvfev",//别人的
    // accessKeySecret: "gu4eUbPrABK4b48vfETESGQJnhI4TM",
    // bucket: "flm158", //要存储的目录名
});

//阿里云oss上传方法及文件名处理
function upload(val, file, nodeImg, ThisImgInput) {
    try {
        var suffix = val.substr(val.indexOf("."));
        var obj = timestamp();
        // var storeAs = 'upload-file/' + "/" + obj + suffix;
        var storeAs = "img/" + obj + suffix;

        client
            .multipartUpload(storeAs, file)
            .then(function(result) {
                var url = result.res.requestUrls[0];
                var length = url.lastIndexOf("?");

                console.log("uploadResult:", result);
                if (result.res.status == 200 || length == "-1") {
                    nodeImg.attr("src", result.url);
                    // console.log(nodeImg);
                    nodeImg[0].style.backgroundImage = "url('')"; //清除无图提示背景写出地址到img
                    ThisImgInput.attr("value", result.url); //写出地址到input
                    ThisImgInput.val(result.url);
                    ThisImgInput.html(result.url);
                    ThisImgInput.text(result.url);
                } else {
                    // console.log(result.res);
                    Toast("上传失败！", "error", 2000);
                }
            })
            .catch(function(err) {
                console.log(err);
            });
    } catch (error) {
        console.log(error);
    }
}

function timestamp() {
    var time = new Date();
    var y = time.getFullYear();
    var m = time.getMonth() + 1;
    var d = time.getDate();
    var h = time.getHours();
    var mm = time.getMinutes();
    var s = time.getSeconds();
    return "" + y + add0(m) + add0(d) + add0(h) + add0(mm) + add0(s);
}

function add0(m) {
    return m < 10 ? "0" + m : m;
}

//压缩图片方法  实际压缩不了
function compressImg(imgUrl, imgfFile, thisIMg) {
    var src;
    var fileSize = parseFloat(parseInt(imgfFile["size"]) / 1024).toFixed(2);
    var read = new FileReader();
    read.readAsDataURL(imgfFile);
    read.onload = function(e) {
        var img = new Image();
        img.src = e.target.result;
        img.onload = function() {
            //默认按比例压缩
            var w = this.width,
                h = this.height;
            //生成canvas
            var canvas = document.createElement("canvas");
            var ctx = canvas.getContext("2d");
            var base64;
            // 创建属性节点
            canvas.setAttribute("width", w);
            canvas.setAttribute("height", h);
            ctx.drawImage(this, 0, 0, w, h);
            // if (fileSize < 100) {
            //如果图片小于一兆 那么不执行压缩操作
            base64 = canvas.toDataURL(file["type"], 0.1);
            var blob = dataURLtoFile(base64, "image/jpeg");

            return base64;
        };
    };
}

// BASE64与文件互转
function dataURLtoBlob(dataurl) {
    let arr = dataurl.split(","),
        mime = arr[0].match(/:(.*?); /)[1],
        bstr = atob(arr[1]),
        n = bstr.length,
        u8arr = new Uint8Array(n);
    while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
    }
    return new Blob([u8arr], {
        type: mime,
    });
}

// 将blob转换为file
function blobToFile(theBlob, fileName) {
    theBlob.lastModifiedDate = new Date();
    theBlob.name = fileName;
    return theBlob;
}

var canvas = document.createElement("canvas"),
    ctx = canvas.getContext("2d");

function compress(img) {
    canvas.width = img.width;
    canvas.height = img.height;
    //利用canvas进行绘图
    //将原来图片的质量压缩到原先的0.2倍。
    var data = canvas.toDataURL("image/jpeg", 0.2); //data url的形式
    return data;
}

//将base64转换为blob
function dataURLtoFile(dataURI, type) {
    let binary = atob(dataURI.split(",")[1]);
    let array = [];
    for (let i = 0; i < binary.length; i++) {
        array.push(binary.charCodeAt(i));
    }
    return new Blob([new Uint8Array(array)], {
        type: type,
    });
}

// getImgBase64();
// 图片处理
function getImgBase64() {
    //图片转BASE64
    var base64 = "";
    var img = new Image();
    img.src = "images/open.jpg";
    img.onload = function() {
        base64 = image2Base64(img);
        // console.log(base64);
    };
}

// image2Base64(img);
//图片转
function image2Base64(img) {
    //base64转图片
    var canvas = document.createElement("canvas");
    canvas.width = img.width;
    canvas.height = img.height;
    var ctx = canvas.getContext("2d");
    ctx.drawImage(img, 0, 0, img.width, img.height);
    var dataURL = canvas.toDataURL("images/png");
    // alert(dataURL);
    return dataURL;
}